package cn.edu.zafu.bigdata.lekang.shiyan5;

public class ArrayIndexOutOfBoundsExceptionHandling {

    public static void main(String[] args) {
        // 创建一个测试数组
        int[] numbers = {1, 2, 3, 4, 5};

        // 测试正常情况
        try {
            int element = getElement(numbers, 2);
            System.out.println("获取的元素是: " + element);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("错误: " + e.getMessage());
        }

        // 测试异常情况
        try {
            int element = getElement(numbers, 10); // 这个索引超出了数组范围
            System.out.println("获取的元素是: " + element);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }

    public static int getElement(int[] arr, int index) throws ArrayIndexOutOfBoundsException {
        if (index < 0 || index >= arr.length) {
            throw new ArrayIndexOutOfBoundsException("索引 " + index + " 超出了数组范围 [0, " + (arr.length - 1) + "]");
        }
        return arr[index];
    }
}